import java.util.concurrent.SynchronousQueue;

/**
 * 每一行代码，都是改变世界的力量
 *
 * @author 郭帅
 * @date 2022/6/24 10:55 上午
 */
public class SynchronizedQueueTest {

    private static final SynchronousQueue<String> synchronousQueue = new SynchronousQueue<>(true);


    private static void producer() throws InterruptedException {
        int i = 0;
        while (true) {
            Thread.sleep(1000);
            synchronousQueue.put(String.valueOf(i++));
            System.out.println("producer:" + i);
        }
    }

    private static void consumer() throws InterruptedException {
        while (true) {
            String take = synchronousQueue.take();
            System.out.println("thread:" + Thread.currentThread().getName() + " value: " + take);
        }
    }

    public static void main(String[] args) throws InterruptedException {

        Thread producer01 = new Thread(() -> {
            try {
                synchronousQueue.put("producer01");

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        producer01.setName("producer01");

        Thread producer02 = new Thread(() -> {
            try {
                synchronousQueue.put("producer02");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        producer02.setName("producer02");

        Thread consumer01 = new Thread(() -> {
            try {
                consumer();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
//
        Thread consumer02 = new Thread(() -> {
            try {
                synchronousQueue.take();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        consumer01.setName("consumer01");
//        consumer02.setName("consumer02");
        producer01.start();
        producer02.start();
//        Thread.sleep(200);
        consumer01.start();
//        consumer02.start();


        Thread.sleep(100000);
    }
}
